﻿using System;
using System.ComponentModel;
using System.Reflection;

/// <summary>
/// 枚举扩展类
/// </summary>
public static class EnumExtension
{
    /// <summary>
    /// 获取枚举的描述信息
    /// </summary>
    public static string GetDescription(this Enum em)
    {
        Type type = em.GetType();
        FieldInfo fd = type.GetField(em.ToString());
        if (fd == null)
            return string.Empty;
        object[] attrs = fd.GetCustomAttributes(typeof(DescriptionAttribute), false);
        string name = string.Empty;
        foreach (DescriptionAttribute attr in attrs)
        {
            name = attr.Description;
        }
        return name;
    }

    public static T GetEnumByDescription<T>(string description) where T : Enum
    {
        FieldInfo[] fields = typeof(T).GetFields();
        foreach (FieldInfo field in fields)
        {
            object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);    //获取描述属性
            if (objs.Length > 0 && (objs[0] as DescriptionAttribute).Description == description)
            {
                return (T)field.GetValue(null);
            }
        }

        throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", description), "Description");
    }
    
}